const request = require('../../utils/https.js')

var count = 0;
var userId, taxFees1;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        checked2: false,
        goods: [],
        type: 0,
        totalPrice: 0, //总价
        userScore: 0, //仓库余额
        use: 0, //收益余额默认不使用
        account: 0, //收益余额默认不使用
        freightPrice: (0).toFixed(2),
        pointsMoney: (0).toFixed(2),
        totalMoney: (0).toFixed(2), //合计总价
        newtotalPrice: (0).toFixed(2), //折扣优惠价格
        addressId: '',
        email_number: '',
        username: '',
        card_number: '',
        inOrOut: 0, //inOrOut 0国内 1国外 2跨境
        showShopp: false,
        roleList: [
            '是',
            '否'
        ],
        Index: 1,
        actions6: [{
            name: '取消'
        },
            {
                name: '去填写',
                color: '#ed3f14'
            }
        ],
        visible7: false,
        actions7: [{
            name: '取消'
        },
            {
                name: '重新填写',
                color: '#ed3f14'
            }
        ],
        notifyUser: false,
        notifyNum: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const that = this;
        userId = wx.getStorageSync("userId")
        that.setData({
            inOrOut: options.inOrOut,
            count: count
        })


        //查看所有商品列表是否有打折商品 并算出打折优惠价格
        let goods = JSON.parse(wx.getStorageSync('goods'));
        if (options.link == 'gift') {
            console.log('直接买')
            goods.forEach((v) => {
                that.setData({
                    tradeNum: v.tradeNum
                })
            })
        } else {
            console.log('购物车')
            that.setData({
                tradeNum: ''
            })
        }
        var goArry = [];
        goods.forEach((v) => {
            goArry.push({
                skuId: v.skuId,
                num: v.prodNum
            })
        })

        console.log('goArry==>', goArry)
        //税费价格计算STA
        request._post_json(getApp().Api_url + 'goods/tax', {
            userId: userId,
            skus: goArry
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                console.log('税费1111222==>', res.data.data)
                taxFees1 = res.data.data;
            }
        }, function () {
        })
        //税费价格计算END


        var totalPrice = Number(wx.getStorageSync('totalprice')).toFixed(2); //商品总价
        var newtotalPrice = 0; //折扣优惠后的价格

        goods.forEach((v) => {
            newtotalPrice += v.currentPrice * v.prodNum //现价总价
            //判断是不是 升值商品
            if (v.fast) { //是直升
                that.setData({
                    fast: true
                })
            } else { //不是直升
                that.setData({
                    fast: false
                })
            }
        })


        newtotalPrice = newtotalPrice.toFixed(2);
        console.log('newtotalPrice折扣优惠后的价格====>', newtotalPrice)
        let discountPrice = Number(totalPrice - newtotalPrice).toFixed(2) // 折扣优惠多少钱
        console.log('discountPrice折扣价格===>', discountPrice)

        //获取用户VIP等级
        request._get(getApp().Api_url + 'user/getMainInfo', {
            userId: wx.getStorageSync("userId")
        }, function (res) {
            if (res.data.code == 200) {
                // 1.国外商品需要满足支付价格大于等于199 才能够包运费税费,不满199 加上运费税费
                var vipPrice = 0; //VIP优惠价格
                if (options.inOrOut == 1) { // inOrOut 0国内 1国外 2跨境
                    var vipDiscount = res.data.data.seaRankRate; //打折数
                } else {
                    var vipDiscount = res.data.data.rankRate; //打折数
                }

                //判断是否直升
                if (that.data.fast) {
                    vipPrice = 0;
                } else {
                    console.log('goods====>++++', goods)
                    var oneValue;
                    //费直升商品包括两部分(1.都是需要打折的商品 2.有一口价的商品不打折)
                    goods.forEach((v) => {
                        if (v.oneValue) { //一口价的商品不打折
                            oneValue = v.oneValue
                        } else {
                            console.log('currentPrice===>', v.currentPrice)
                            console.log('rankPrice===>', v.rankPrice)
                            if(v.rankPrice!=null){
                                vipPrice += Number((v.currentPrice - v.rankPrice) * v.prodNum);
                            }
                            console.log('vipPrice=====+++++', vipPrice)
                        }
                    })

                    if (oneValue) {
                        console.log('有一口价商品')
                        //一口价商品currentPrice*prodNum 打折商品
                        vipPrice = Number(vipPrice).toFixed(2);
                    } else {
                        console.log('没有一口价商品')
                        vipPrice = Number(newtotalPrice - (newtotalPrice * vipDiscount)).toFixed(2);
                        console.log('vipPrice=====+++++', vipPrice)
                    }
                }
                console.log('vipPrice=====+++++', vipPrice)

                that.setData({
                    inOrOut: options.inOrOut,
                    type: options.type, //type =1 购物车
                    goods: goods,
                    totalPrice: totalPrice, //商品总价
                    vipPrice: vipPrice, //会员优惠多少钱
                    discountPrice: discountPrice //商品折扣优惠
                })


                //调取仓库余额(总价,会员等级优惠,商品本身优惠,税费)
                /* console.log('totalPrice==>', totalPrice)
                console.log('vipPrice==>', vipPrice)
                console.log('discountPrice==>', discountPrice) */
                //当收益余额大于等于合计价格调取
                //用户收益余额接口
                that.userEarnings();
                //获取地址
                that.getAddress();

            }
        }, function () {
        });

    },


    //用户收益余额接口
    userEarnings() {
        const that = this;
        let userId = wx.getStorageSync("userId");
        request._get(getApp().Api_url + 'profit/entry', {
            userId: userId
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                that.setData({
                    totalAmount: res.data.data.totalAmount //收益余额
                })
            }
        }, function () {
        })
    },

    //是否使用收益余额 开关
    onChange2(event) {
        // 需要手动对 checked1 状态进行更新
        const that = this;
        that.setData({
            checked2: event.detail
        });

        if (event.detail) { //使用收益余额
            that.setData({
                totalMoney: 0.00,
                account: 1
            })
        } else { //不使用收益
            that.setData({
                totalMoney: that.data.newPaytotalPrice,
                account: 0
            })
        }
    },


    //去新增地址页
    goMail() {
        const that = this;
        //跳走后需要保存当前订单页的数据
        if (that.data.dataAdderss !=null && that.data.dataAdderss !=undefined &&that.data.dataAdderss.length > 0) {
            wx.navigateTo({
                url: '/pages/address/address?address=1' + '&type=1'
            })
        } else {
            wx.navigateTo({
                url: '/pages/mail/mail?addressId=' + ' ' + '&add=oneAdd'
            })
        }

    },
    payInfo() {
        //跳走后需要保存当前订单页的数据
        wx.navigateTo({
            url: '/pages/payInfo/payInfo?type=order'
        })
    },
    //去地址列表页
    goAddress() {
        wx.navigateTo({
            url: '/pages/address/address?address=1' + '&type=1'
        })
    },
    //切换是否支付人信息
    getRole(event) {
        const that = this;
        let Index = event.currentTarget.dataset.index;

        if (Index == 0) {
            that.setData({
                username: that.data.selectedAddress.userName,
                phone: that.data.selectedAddress.mobile,
                card_number: ''
            })
        } else {
            that.setData({
                username: '',
                phone: '',
                card_number: ''
            })
        }
        that.setData({
            Index: Index
        })

    },


    //地址
    getAddress() {
        const that = this;
        request._get(getApp().Api_url + 'userAddress/mine', {
            userId: wx.getStorageSync("userId"),
            type: 0, //0 订单提交需要地址带价格
            tradeType: that.data.inOrOut //贸易方式
        }, function (res) {
            if (res.data.errCode == 200) {
                let dataAdderss = res.data.data;
                that.setData({
                    dataAdderss: dataAdderss
                })

                if (dataAdderss.length > 0) {
                    console.log('地址不为空')
                    dataAdderss.forEach((v) => {
                        //判断上级返回页面 addressId 为真用本身 不为真用isDefault
                        let addressId = wx.getStorageSync('addressId')
                        if (addressId) {
                            if (v.addressId == addressId) { //选中的地址
                                that.setData({
                                    selectedAddress: v,
                                    addressId: v.addressId,
                                    fee: v.fee,
                                    code: v.code
                                })
                                that.getFee(v.code);
                            }
                        } else {
                            if (v.isPriority == 1 /* || v.isDefault == 1 */) { //上次下单地址／或者默认地址
                                console.log('有上次下单地址')
                                that.setData({
                                    selectedAddress: v,
                                    addressId: v.addressId,
                                    fee: v.fee,
                                    code: v.code
                                })
                                that.getFee(v.code);
                            } else {
                                console.log('没有上次下单地址')
                            }
                        }
                    })
                } else {
                    console.log('地址为空')
                    //地址为空code 传默认的 E
                    that.getFee('E');
                }


            }
        }, function () {
        });
    },


    /*
    资费邮费接口
    */
    getFee(code) {
        const that = this;
        //邮费 税务接口
        request._get(getApp().Api_url + 'goods/fee', {
            code: code,
            tradeType: that.data.inOrOut
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                var feeData = res.data.data;

                /* console.log('邮费资费feeData===>', feeData) */
                var tradeType = feeData.tradeType //贸易方式 0国内 1海外 2跨境
                var trFee = feeData.gateFeeRate; //税率 跨境2 用
                var fullMoney = feeData.exGateFullMoney; //海外1用 最低包税费价格
                var payMoney = feeData.exGateAppendMoney; //海外1用 不够包邮税标准需要补的价格
                var exFee = feeData.exFee //运费 国内0跨境2 用
                var exUse = feeData.exUse //跨境2用 商家是否承担物流费 0 商家不承担 不划掉展示原来 1商家承担 划掉展示0.00
                var gateUse = feeData.gateUse //跨境2用 商家是否承担税费 0 商家不承担 不划掉展示原来 1商家承担 划掉展示0.00
                var exGateUse = feeData.exGateUse // 海外1用 商家是否承担运费和税费之和 0 商家不承担 不划掉展示原来 1商家承担 划掉展示0.00

                //totalPrice商品总价，vipPrice会员优惠多少钱，discountPrice商品折扣优惠
                var paytotalPrice = that.data.totalPrice - that.data.vipPrice - that.data.discountPrice //
                var newPaytotalPrice = 0;
                //不同贸易方式的计算方法
                if (tradeType == 1) {
                    console.log('==国外===')
                    //不够199 运费+税费 展示不划掉 够199展示划掉

                    if (fullMoney > paytotalPrice) { //不够最低标准收费
                        var newPaytotalPrice = paytotalPrice + payMoney
                    } else {
                        var newPaytotalPrice = paytotalPrice
                    }

                    that.setData({
                        disabled: true,
                        totalMoney: Number(newPaytotalPrice).toFixed(2)
                    })

                } else if (tradeType == 0) {
                    console.log('===国内的===')
                    //0  的把小健给的运费 展示出来exUse=1不划 exUse=0 划掉

                    if (exUse == 0) { //商家不承担邮费
                        var newPaytotalPrice = paytotalPrice + exFee;
                    } else { //商家承担邮费
                        var newPaytotalPrice = paytotalPrice;
                    }

                    //国内能使用抵扣
                    if (Number(that.data.totalAmount) > Number(newPaytotalPrice)) {
                        console.log('收益余额大于总价')
                        that.setData({
                            disabled: false,
                            checked2: true,
                            totalMoney: Number(0).toFixed(2),
                            account: 1


                        })
                    } else {
                        console.log('收益余额小于总价')
                        that.setData({
                            disabled: true,
                            totalMoney: Number(newPaytotalPrice).toFixed(2)
                        })
                    }


                } else if (tradeType == 2) {
                    console.log('====跨境的=====')

                    //1.运费税费花掉 展示0元
                    if (gateUse == 0) { //商家不承担税费
                        if (exUse == 0) { //商家不承担邮费
                            var newPaytotalPrice = paytotalPrice + exFee + taxFees1
                        } else { //商家承担邮费
                            var newPaytotalPrice = paytotalPrice + taxFees1
                        }
                    } else { //商家承担
                        if (exUse == 0) { //商家不承担邮费
                            var newPaytotalPrice = paytotalPrice + exFee
                        } else { //商家承担邮费
                            var newPaytotalPrice = paytotalPrice
                        }
                    }
                    that.setData({
                        disabled: true,
                        totalMoney: Number(newPaytotalPrice).toFixed(2)
                    })
                }


                that.setData({
                    exUse: exUse,
                    gateUse: gateUse,
                    paytotalPrice: paytotalPrice,
                    newPaytotalPrice: Number(newPaytotalPrice).toFixed(2),
                    totalAmount: Number(that.data.totalAmount).toFixed(2),
                    tradeType: tradeType,
                    fullMoney: fullMoney,
                    payMoney: payMoney,
                    exFee: exFee,
                    taxFees1: taxFees1,
                    trFee: trFee
                })

            }
        }, function () {
        });

    },

    /*
      获取身份证号
    */
    getCard(e) {
        const that = this;
        that.setData({
            card_number: e.detail
        })
    },
    //获取手机号
    getPhone(e) {
        const that = this;
        that.setData({
            phone: e.detail
        })
    },
    /*
      获取真实姓名
    */
    getUserName(e) {
        const that = this;
        that.setData({
            username: e.detail
        })
    },


    //提交订单的贸易方式
    checkOrder() {
        const that = this;
        if (that.data.inOrOut == 1 || that.data.inOrOut == 2) {
            //新增判断单笔消费超过5k没有

            if (that.data.totalMoney > 5000.00) {
                wx.showToast({
                    title: '由于是跨境商品单笔交易不能超过5000元人民币',
                    duration: 2000,
                    icon: 'none'
                })
                return false;
            }


            console.log('有国外和跨境 商品==>')
            //有国外和跨境 商品
            //判断有没有填支付人信息

            if (that.data.nameHas == 1) { //有
                if (that.data.sameWx == 1) { //绑定成功
                    that.postOrder();
                } else {
                    that.setData({
                        visible7: true
                    })
                }
            } else { //没有
                that.setData({
                    visible6: true
                })
            }

        } else {
            console.log('国内商品==>')
            //国内商品
            //查看是否开启收益抵扣
            if (that.data.checked2) { //开启了
                console.log('开启了抵扣')
                that.setData({
                    showShopp: true
                })
            } else {
                console.log('未开开启了抵扣')
                that.postOrder();
            }
        }

    },

    handleClick6({
                     detail
                 }) {
        const that = this;
        if (detail.index === 0) {
            that.setData({
                visible6: false
            });
            console.log('取消')
        } else {
            console.log('去填写')
            wx.navigateTo({
                url: '/pages/payInfo/payInfo',
            })
            that.setData({
                visible6: false
            });
        }
    },

    handleClick7({
                     detail
                 }) {
        const that = this;
        if (detail.index === 0) {
            that.setData({
                visible7: false
            });
            console.log('取消')
        } else {
            console.log('重新绑定')
            wx.navigateTo({
                url: '/pages/payInfo/payInfo',
            })
            that.setData({
                visible7: false
            });
        }
    },


    //提交订单
    postOrder() {
        const that = this;
        let temp, prefix
        let regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        let regIdNo1 = /^[1-9][0-9]{5}$/;
        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        var card_number = that.data.card_number;
        var email_number = that.data.email_number;
        var username = that.data.username;
        var phone = that.data.phone;
        //关闭弹框
        that.setData({
            showShopp: false
        })

        if (that.data.addressId === '') {
            wx.showToast({
                title: '请选择或填写地址！',
                icon: 'none'
            })
            return false;
        }

        if (that.data.inOrOut == 1 || that.data.inOrOut == 2) {
            //有国外和跨境 商品

            if (!username) {
                wx.showToast({
                    title: '请填写姓名',
                    icon: 'none'
                })
                return false;
            }
            if (!myreg.test(phone)) {
                wx.showToast({
                    title: '手机号有误',
                    icon: 'none'
                })
                return false;
            }
            if (!regIdNo.test(card_number)) {
                wx.showToast({
                    title: '身份证号填写有误',
                    icon: 'none'
                })
                return false;
            }
            /*if (!regIdNo1.test(email_number)) {
              wx.showToast({
                title: '邮编填写有误',
                icon: 'none'
              })
              return false;
            } */
        } else {
            //国内商品
            var card_number = 'null';
            var email_number = 'null';
            var username = 'null';
            var phone = 'null'
        }


        if (that.data.type == 1) { //购物车
            const goodsid = [];
            that.data.goods.forEach(item => {
                goodsid.push(item.cartId);
            })

            temp = {
                "cart": {
                    "userId": wx.getStorageSync("userId"),
                    "ids": goodsid,
                    "addressId": that.data.addressId,
                    "idCard": card_number,
                    "realName": username,
                    "phone": phone,
                    "use": that.data.use, //1使用 0不适用
                    "account": that.data.account, //1使用 0不适用
                    "tradeNum": '001'
                }
            }
            if (!that.checkData(temp.cart)) {
                wx.showToast({
                    title: '参数不全，不能提交！',
                    icon: 'none'
                })
                return false;
            }

        } else {
            //立即购买下单
            //addressId
            //idCard
            //num
            //prodId 商品id
            //skuId 商品sku值
            //userId
            temp = {
                "once": {
                    "userId": wx.getStorageSync("userId"),
                    "prodId": that.data.goods[0].prodId,
                    "num": that.data.goods[0].prodNum,
                    "addressId": that.data.addressId,
                    "skuId": that.data.goods[0].skuId,
                    "idCard": card_number,
                    "realName": username,
                    "phone": phone,
                    "use": that.data.use, //仓库余额 1使用 0不适用
                    "account": that.data.account, //收益余额 1使用 0不适用
                    "tradeNum": that.data.tradeNum
                }
            }

            if (!that.checkData(temp.once)) {
                wx.showToast({
                    title: '参数不全，不能提交！',
                    icon: 'none'
                })
                return false;
            }

        }

        wx.setStorageSync("amount", that.data.totalPrice + that.data.freightPrice - that.data.points / 10)

        if (that.data.fast) { //直升
            var orderUrl = "order/genFast"
        } else {
            var orderUrl = "order/gen2"
        }

        let needCheck = that.data.notifyUser;
        let crossOrder = that.data.tradeNum;
        if (crossOrder == '002' || crossOrder == '003') {
            if (!that.data.notifyUser) {
                that.setData({
                    notifyUser: true
                });
                needCheck = false;
            }
        } else {
            needCheck = true;
        }

        if (needCheck) {
            request._post_json(getApp().Api_url + orderUrl, temp, (res) => {

                let params = res.data.data;
                console.log('res===>', res.data)

                if (res.data.errCode == 200) {
                    if (params.needPay == 1) { //直接积分抵扣
                        wx.redirectTo({
                            url: '/pages/pay_success/pay_success?orderMoney=0.00' + '&orderId=' + params.orderId + '&needPay=' + params.needPay
                        })
                    } else { //微信支付
                        wx.redirectTo({
                            url: '/pages/checkstand/checkstand?orderMoney=' + params.orderMoney + '&orderId=' + params.orderId + '&needPay=' + params.needPay
                        })
                        //这里判断是小程序支付还是跳转webview支付
                        //let ImgLinks = 'http://192.168.0.90/2019/pay.html?money=754.20&wxUrl=https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx011623493108095806b109fe1439527400&package=2541672566';

                        /* wx.navigateTo({
                          url: '/pages/webview_1/webview_1?money=1234567'
                        }) */
                    }
                } else {
                    wx.showToast({
                        title: res.data.errMsg,
                        icon: 'none'
                    })
                }


            }, (xhr) => {

            })
        }


    },
    shutToast() {
        const that = this;
        that.setData({
            showShopp: false
        })
    },


    closeNotify() {
        const that = this;
        that.setData({
            notifyNum: 2
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const that = this;
        that.getAddress(); //获取地址接口
        that.getPay(); //
        console.log('我是onShow=======>111')
        that.setData({
            checked2: false,
            account: 0
        })
    },
    //获取下单人姓名身份证号
    getPay() {
        const that = this;
        //获取下单人姓名和身份证号码
        request._get(getApp().Api_url + 'user/hasVerify', {
            userId: wx.getStorageSync("userId")
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                console.log('获取电话手机号==>', res.data.data)
                that.setData({
                    username: res.data.data.username,
                    card_number: res.data.data.idCard,
                    phone: res.data.data.phone,
                    nameHas: res.data.data.has, //0 没有提交过，1提交过
                    sameWx: res.data.data.sameWx //0没绑定成功，1绑定成功
                })
            }
        }, function () {
        })
    },


    // 去修改地址
    reEditAddress(tar) {
        const that = this;
        var addressId = tar.currentTarget.dataset.aid;
        console.log("地址id是:" + addressId)
        wx.navigateTo({
            url: '/pages/mail/mail?addressId=' + addressId + '&add=oneAdd'
        })
    },
    // 确认后的提交订单
    reConfirm() {
        const that = this;
        that.setData({
            notifyUser: true
        });
        that.postOrder();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        wx.removeStorageSync('addressId')
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    checkData(data) {
        for (let key in data) {
            if (data[key] === '' || data[key] === undefined) {
                return false;
            }
        }
        return true;
    }
})